import * as Blockly from 'blockly/core';

// 覆盖原有的TFT_init_with_pin
export const TFT_init_with_pin = function () {
    const PIN_CS = this.getFieldValue('CS');
    const PIN_DC = this.getFieldValue('DC');
    const PIN_RST = this.getFieldValue('RST');
    const PIN_CLK = Blockly.Arduino.valueToCode(this, 'CLK', Blockly.Arduino.ORDER_ATOMIC);
    const PIN_MOSI = Blockly.Arduino.valueToCode(this, 'MOSI', Blockly.Arduino.ORDER_ATOMIC);
    const TYPE = this.getFieldValue('TYPE');
    let icType = 'ST7735';
    if (TYPE.indexOf('ST7796') !== -1)
        icType = 'ST7796';
    else if (TYPE.indexOf('INITR') !== -1)
        icType = 'ST7735';
    else
        icType = 'ST7789';
    Blockly.Arduino.definitions_["include_Adafruit_GFX"] = '#include <Adafruit_GFX.h>';
    Blockly.Arduino.definitions_["include_Adafruit_tft"] = '#include <Adafruit_' + icType + '.h>';
    Blockly.Arduino.definitions_["include_SPI"] = '#include <SPI.h>';
    Blockly.Arduino.setups_["setup_spi_init_" + PIN_CLK + PIN_MOSI] = `SPI.setSCK(${PIN_CLK});\n  SPI.setTX(${PIN_MOSI});`;
    Blockly.Arduino.definitions_['var_declare_Adafruit_tft'] = 'Adafruit_' + icType + ' tft = Adafruit_' + icType + '(' + PIN_CS + ', ' + PIN_DC + ', ' + PIN_RST + ');';
    Blockly.Arduino.setups_["setup_tft_init"] = 'tft.' + (icType === 'ST7735' ? 'initR' : 'init') + '(' + TYPE + ');';
    Blockly.Arduino.setups_["setup_tft_fillScreen"] = 'tft.fillScreen(0x0000);';
    Blockly.Arduino.definitions_["include_U8g2_for_Adafruit_GFX"] = '#include <U8g2_for_Adafruit_GFX.h>';
    Blockly.Arduino.definitions_['var_declare_U8G2_FOR_ADAFRUIT_GFX'] = 'U8G2_FOR_ADAFRUIT_GFX u8g2_for_adafruit_gfx;';
    Blockly.Arduino.setups_["setup_u8g2_for_adafruit_gfx"] = 'u8g2_for_adafruit_gfx.begin(tft);';
    var code = '';
    return code;
};